'use strict';
let db = uniCloud.database();
let checkres = false;
let dbCmd = db.command;
let oneres = "";
let currentZero = new Date().setHours(0, 0, 0, 0) // 获取当天零点
let isDel = true;

//查询并删除
async function checkAndDelet(obj) {
	for (let i = 0; i < obj.members.length; i++) {
		let onecheck = await db.collection("count").field({
			"_id": true
		}).where({
			school: obj.school,
			floor: obj.floor,
			roomNum: obj.roomNum,
			roomtype: obj.roomtype,
			stname: obj.members[i].name,
			uid: obj.uid,
			createtime: dbCmd.gt(currentZero) //查询今天零点以后是否存在记录
		}).get();
		if (onecheck.affectedDocs == 1) {
			let delres = await db.collection("count").where({
				_id: onecheck.data[0]._id
			}).remove(); //删除当天已有记录保持当天记录为最新记录
			if (delres.deleted != 1) {
				isDel = false;
				break;
			}
		}
	}
	return isDel;
}


//判断数据是否新增成功
async function checkRoom(obj) {
	for (let i = 0; i < obj.members.length; i++) {
		let onecheck = await db.collection("count").add({
			school: obj.school,
			floor: obj.floor,
			roomNum: obj.roomNum,
			roomtype: obj.roomtype,
			stname: obj.members[i].name,
			stType: obj.members[i].type,
			roomid:obj.roomid,
			uid: obj.uid,
			createtime: obj.createtime
		});
		if (onecheck) {
			checkres = true;
		} else {
			checkres = false;
			break;
		}
	}
	return checkres;
}

exports.main = async (event, context) => {
	if (event.type == "getSchoolArr") {
		return await db.collection("room").field({
			'school': true
		}).where({
			uid: event.uid
		}).get();
	} else if (event.type == "checkRoom") {

		//先查询当天是否有记录，如果有记录先删除记录再更新
		if (await checkAndDelet(event)) {
			//调用函数checkRoom
			return await checkRoom(event);
		}

	} else if (event.type == "getOneRoom") {
		return await db.collection("room").where({
			_id: event.roomId
		}).get();
	} else {
		for (let key in event) {
			if (event[key] == "选择校区" || event[key] == 0) {
				delete event[key];
			}
		}
		return await db.collection("room").where(event).get();
	}

};